<template>
  <div>
    <div class="box-border p-12px">
      <div>
        <SubTitle :title="descInfo.baseTitle" />
        <el-descriptions :column="descInfo.column">
          <el-descriptions-item
            :label="item.label"
            v-for="(item, index) in descInfo.columns"
            :key="index"
          >
            <span v-if="item.key == 'ip'"> {{ descInfo.data.ip }}:{{ descInfo.data.port }} </span>
            <span v-else-if="item.key == 'source'">
              {{ sourceMap.has(descInfo.data.source) ? sourceMap.get(descInfo.data.source) : '--' }}
            </span>
            <span v-else-if="item.key == 'fileFingerprint'">
              <el-tooltip placement="top" :content="descInfo.data.md5?.toString() || '无'">
                <span>MD5,</span>
              </el-tooltip>
              <el-tooltip placement="top" :content="descInfo.data.kfs?.toString() || '无'">
                <span>KFS,</span>
              </el-tooltip>
              <el-tooltip placement="top" :content="descInfo.data.pfs?.toString() || '无'">
                <span>PFS,</span>
              </el-tooltip>
              <el-tooltip placement="top" :content="descInfo.data.psa?.toString() || '无'">
                <span>PSA</span>
              </el-tooltip>
            </span>
            <span v-else>
              {{ descInfo.data[item.key] || '--' }}
            </span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="mt-32px" v-if="props.params.auditType == 'asset'">
        <SubTitle title="分类状态" />
        <el-table :data="classTable" style="width: 100%">
          <el-table-column label="" prop="title" />
          <el-table-column label="总数">
            <template #default="scope">
              <div>{{ scope.row.total }} </div>
            </template>
          </el-table-column>
          <el-table-column label="已分类">
            <template #default="scope">
              <div>{{ scope.row.classified }} </div>
            </template>
          </el-table-column>
          <el-table-column label="未分类">
            <template #default="scope">
              <div>{{ scope.row.unclassified }} </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="mt-32px" v-if="props.params.auditType == 'asset'">
        <SubTitle title="分级状态" />
        <el-table :data="levelTable" style="width: 100%">
          <el-table-column label="" prop="title" />
          <el-table-column label="总数">
            <template #default="scope">
              <div>{{ scope.row.total }} </div>
            </template>
          </el-table-column>
          <el-table-column label="已分级">
            <template #default="scope">
              <div>{{ scope.row.classified }} </div>
            </template>
          </el-table-column>
          <el-table-column label="未分级">
            <template #default="scope">
              <div>{{ scope.row.unclassified }} </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="mt-32px" v-if="props.params.auditType !== 'asset'">
        <SubTitle title="分类分级状态" />
        <!-- <el-descriptions :column="1">
          <el-descriptions-item label="分类">{{
            props.params.handClassificationName || props.params.classificationName || '--'
          }}</el-descriptions-item>
          <el-descriptions-item label="分级">{{
            props.params.handLevelName || props.params.levelName || '--'
          }}</el-descriptions-item>
        </el-descriptions> -->
        <el-descriptions column="1" class="mt-16px">
          <el-descriptions-item
            v-for="(columnItem, columnIndex) in columnList"
            :key="columnIndex"
            :label="columnItem.name"
          >
            <span v-if="columnItem.index == '1'">
              <!-- {{ descInfo.data.handClassificationName }} -->
              {{ classRender }}
            </span>
            <span v-else-if="columnItem.index == '2'">
              <!-- {{ descInfo.data.handLevelName }} -->
              {{ levelNameRender }}
            </span>
            <span v-else>
              {{ descInfo.data[`institutionFiled${columnItem.index}`] || '--' }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item
            v-for="(extendItem, extendIndex) in extendList"
            :key="extendIndex"
            :label="extendItem.name"
          >
            <span v-if="extendItem.index == '3'">
              <!-- {{ descInfo.data.deadlineLevelName }} -->
              {{ deadlineLevelNameRender }}
            </span>
            <span v-else>
              {{ descInfo.data[`field${extendItem.index}`] || '--' }}
            </span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="mt-32px">
        <SubTitle title="流程" />
        <el-form ref="formRef" :rules="rules" :model="form" label-width="100px" class="mt-12px">
          <el-form-item label="流程选择" required prop="auditStatus">
            <el-radio-group v-model="form.auditStatus">
              <el-radio label="1">通过</el-radio>
              <el-radio label="2">不通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核意见" prop="reason">
            <ns-input
              type="textarea"
              v-model="form.reason"
              placeholder="请输入审核意见"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div>
      <el-button type="primary" @click="confirm">确定</el-button>
      <el-button @click="closeOutDrawer">取消</el-button>
    </div>
  </div>
</template>
<script lang="tsx" setup>
import { assetLevelCountDB, assetLevelCountFile } from '@/api/assetList'
import * as TaskApi from '@/api/bpm/task'
import * as assuranceApi from '@/api/dataStandards/assurance/index'
import { valueConfFieldValue } from '@/api/dataStandards/assuranceValue/index'
import { infoPage } from '@/api/dataStandards/info/index'
import { levelPage } from '@/api/strategyManage/level/index'
import SubTitle from '@/components/SubTitle/index.vue'
import { sourceMap } from '@/utils/dict'
const message = useMessage() // 消息弹窗
const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  },
  closeOutDrawer: Function
})

const columnList = ref([])
const extendList = ref([])

const formRef = ref()
const form = ref({
  auditStatus: '1',
  reason: '',
  id: ''
})
const rules = {
  auditStatus: [{ required: true, message: '审核意见不能为空', trigger: 'blur' }]
}

const classTable = ref([
  {
    title: '数据表',
    total: 0,
    classified: 0,
    unclassified: 0
  },
  {
    title: '数据字段',
    total: 0,
    classified: 0,
    unclassified: 0
  }
])
const levelTable = ref([
  {
    title: '数据表',
    total: 0,
    classified: 0,
    unclassified: 0
  },
  {
    title: '数据字段',
    total: 0,
    classified: 0,
    unclassified: 0
  }
])

const descInfo = reactive({
  column: 1,
  columns: [
    { label: '数据源名称：', key: 'name' },
    {
      label: '资产地址：',
      key: 'ip'
    },
    { label: '资产类型：', key: 'assetTypeName' },
    { label: '数据源来源：', key: 'source' },
    { label: '归属机构：', key: 'deptName' },
    { label: '归属系统：', key: 'sysName' }
  ],
  data: {},
  baseTitle: '数据库基本信息'
})

const confirm = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      console.log('valid', valid)
      if (form.value.auditStatus === '1') {
        await TaskApi.approveTask({ id: props.params.processId, reason: form.value.reason })
        message.success('审批通过成功')
        props.params.callBack()
        props.closeOutDrawer()
      } else {
        await TaskApi.rejectTask({ id: props.params.processId, reason: form.value.reason })
        message.success('审批不通过成功')
        props.params.callBack()
        props.closeOutDrawer()
      }
    }
  })
}

// 获取分类分级数据
const getCount = async () => {
  if (props.params.id && props.params.datasourceType == '1') {
    const data = await assetLevelCountDB({ id: props.params.id })
    console.log('data', data)
    levelTable.value = [
      {
        title: '数据表',
        total: data[0].totalCount,
        classified: data[0].level,
        unclassified: data[0].unLevel
      },
      {
        title: '数据字段',
        total: data[1].totalCount,
        classified: data[1].level,
        unclassified: data[1].unLevel
      }
    ]
    classTable.value = [
      {
        title: '数据表',
        total: data[0].totalCount,
        classified: data[0].classification,
        unclassified: data[0].unClassification
      },
      {
        title: '数据字段',
        total: data[1].totalCount,
        classified: data[1].classification,
        unclassified: data[1].unClassification
      }
    ]
  } else if (props.params.id && props.params.datasourceType == '2') {
    // 文件服务器
    const data = await assetLevelCountFile({ id: props.params.id })
    console.log('data', data)
    levelTable.value = [
      {
        title: '分级',
        total: data.totalCount,
        classified: data.level,
        unclassified: data.unLevel
      }
    ]
    classTable.value = [
      {
        title: '分类',
        total: data.totalCount,
        classified: data.classification,
        unclassified: data.unClassification
      }
    ]
  }
}

// 获取制度信息字段列表
const getAssuranceList = async () => {
  const data = await assuranceApi.assurancePage({
    dataStandardId: props.params.template,
    display: 1,
    page: 1,
    pageSize: 20
  })
  if (data.length > 0) {
    columnList.value = data
  } else {
    columnList.value = []
  }
}

// 获取模板扩展字段列表
const getInfoList = async () => {
  const data = await infoPage({
    page: 1,
    pageSize: 20,
    dataStandardId: props.params.template,
    display: '1'
  })
  extendList.value = data.map((item) => {
    return {
      ...item,
      presetContentMap: item.presetContent ? JSON.parse(item.presetContent) : []
    }
  })
}

// 获取等级下拉列表
const levelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  levelList.value = data
}
// 获取分类树，用于分类字段回显
// 获取模板下的分类树
const classificationList = ref([])
const getClassificationTree = async () => {
  classificationList.value = await valueConfFieldValue({
    dataStandardId: props.params.template,
    type: '1'
  })
  console.log('classificationList.value', classificationList.value)
}

// 回显等级
const levelNameRender = computed(() => {
  const level = levelList.value.find((item) => {
    return item.levelCode == props.params.institutionFiled2
  })
  return level?.levelName
})
// 回显到期后等级
const deadlineLevelNameRender = computed(() => {
  const level = levelList.value.find((item) => {
    return item.levelCode == props.params.field3
  })
  return level?.levelName
})
// 回显分类
const classRender = computed(() => {
  const foundNode = classificationList.value.find(
    (item) => item.key == props.params.institutionFiled1
  )
  if (foundNode) {
    return foundNode.value
  } else {
    return ''
  }
})

onMounted(() => {
  getCount()
  getAssuranceList()
  getInfoList()
  getLevelList()
  getClassificationTree()
  descInfo.data = props.params
  form.value.id = props.params.id
  console.log('descInfo.data', descInfo.data)
  // auditType file(文件),asset（数据库，文件服务器）,passFile,passColumn,passTable（数据管理过来的）
  if (props.params.auditType === 'fileServer') {
    descInfo.baseTitle = '文件服务器基本信息'
  } else if (props.params.auditType === 'file' || props.params.auditType === 'passFile') {
    descInfo.baseTitle = '基本信息'
    descInfo.columns = [
      { label: '文件名称：', key: 'fileName' },
      { label: '文件类型：', key: 'fileType' },
      { label: '文件大小：', key: 'fileSize' },
      { label: '文件指纹：', key: 'fileFingerprint' },
      { label: '归属机构：', key: 'deptName' },
      { label: '归属系统：', key: 'sysName' },
      { label: '数据标准：', key: 'templateName' }
    ]
  } else if (props.params.auditType === 'passColumn') {
    descInfo.baseTitle = '基本信息'
    descInfo.columns = [
      { label: '字段名称：', key: 'column' },
      { label: '字段类型：', key: 'columnType' },
      { label: '字段描述：', key: 'comment' },
      { label: '所属表：', key: 'table' },
      { label: '所属schema：', key: 'schema' },
      { label: '所属库：', key: 'database' },
      { label: '归属机构：', key: 'deptName' },
      { label: '归属系统：', key: 'sysName' },
      { label: '数据标准：', key: 'templateName' }
    ]
  } else if (props.params.auditType === 'passTable') {
    descInfo.baseTitle = '基本信息'
    descInfo.columns = [
      { label: '表名称：', key: 'table' },
      { label: '表描述：', key: 'remark' },
      { label: '所属schema：', key: 'schema' },
      { label: '所属库：', key: 'database' },
      { label: '归属机构：', key: 'deptName' },
      { label: '归属系统：', key: 'sysName' },
      { label: '数据标准：', key: 'templateName' }
    ]
  }
})
</script>

<style scoped lang="scss">
:deep(.el-table .el-form-item--default) {
  margin-bottom: 0 !important;
}
</style>
